package com.android.lovely.framework

import android.os.Bundle
import android.util.Log
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import androidx.fragment.app.Fragment
import androidx.lifecycle.lifecycleScope
import androidx.viewbinding.ViewBinding
import com.android.lovely.ext.TAG
import com.android.lovely.ext.saveAs
import com.android.lovely.ext.saveAsUnChecked
import com.kotlin.extensions.coroutine.CoroutineExt.launchSafety
import java.lang.reflect.ParameterizedType

/**
 *
 * @author why
 * @date 2025/3/6 19:17
 */
abstract class BaseFragment<DB : ViewBinding> : Fragment() {
    //This property is only valid between onCreateView and onDestroyView.
    lateinit var mBinding: DB

    override fun onCreateView(
        inflater: LayoutInflater,
        container: ViewGroup?,
        savedInstanceState: Bundle?
    ): View {
        return getContentView(
            inflater,
            container
        )
    }

    override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
        super.onViewCreated(view, savedInstanceState)
        try {
            initView()
            lifecycleScope.launchSafety{
                initData()
            }
        } catch (e: Exception) {
            Log.e(TAG, e.message.toString())
        }
    }

    abstract fun initView()

    abstract suspend fun initData()

    private fun getContentView(inflater: LayoutInflater, container: ViewGroup?): View {
        val type = javaClass.genericSuperclass
        val vbClass: Class<DB> = type!!.saveAs<ParameterizedType>().actualTypeArguments[0].saveAs()
        val method = vbClass.getDeclaredMethod("inflate", LayoutInflater::class.java)
        mBinding = method.invoke(this, layoutInflater)?.saveAsUnChecked()
            ?: throw NullPointerException("Binding cannot be null")
        return mBinding.root
    }


    override fun onDestroyView() {
        super.onDestroyView()
    }
}